package dbmanager;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import framework.NomUser;

public class AccountManager extends DatabaseObjectManager {
	public static boolean login(String username, String password) throws SQLException {
		ResultSet rs = dbm.sendQuery("select * from nom_user where username='"
				+ username + "' and password='" + password + "'");
		if (rs.next()) {
			int id = Integer.parseInt(rs.getString("id"));
			String name = rs.getString("name");
			String email = rs.getString("email");
			boolean isAdmin = isAdmin(username);
			
			NomUser user = new NomUser(id, username, email, name, null, isAdmin);
			// Get a list of friends too?
			DatabaseObjectManager.setLogin(user);
			return true;
		} else {
			return false;
		}
	}

	public static boolean userExists(String username) throws SQLException {
		ResultSet rs = dbm.sendQuery("select * from nom_user where username='"
				+ username + "'");
		if (rs.next()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return True if the NOM user account is created
	 * @throws SQLException
	 */
	public static boolean createUser(String username, String password, String email,
			String name) throws SQLException {
		try {
			dbm
					.sendInsertQuery("insert into nom_user(username,password,email,name) values ('"
							+ username
							+ "','"
							+ password
							+ "','"
							+ email
							+ "','" + name + "')");
			return true;
		} catch (MySQLIntegrityConstraintViolationException e) {
			return false;
		}
	}

	public static boolean isAdmin(String username) throws SQLException {
		ResultSet rs = dbm.sendQuery("select * from nom_user where username='"
				+ username + "' and admin=1");
		if (rs.next()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Deletes the user account.
	 * 
	 * @param username
	 * @return True if the username existed and was deleted, false otherwise
	 * @throws SQLException
	 */
	public static boolean deleteUser(String username) throws SQLException {
		if (userExists(username)) {
			dbm.sendInsertQuery("delete from nom_user where username = '"
					+ username + "'");
			return true;
		} else {
			return false;
		}
	}

	public static void updateEmail(String email) throws SQLException {
		dbm.sendInsertQuery("update nom_user set email='"+email+"' where id="+AccountManager.getLogin().getId());
	}
	public static void updatePassword(String password) throws SQLException {
		dbm.sendInsertQuery("update nom_user set password='"+password+"' where id="+AccountManager.getLogin().getId());
	}
	
	public static void main(String[] args) throws SQLException {
		DatabaseObjectManager.connect();
		System.out.print(AccountManager.isAdmin("thomas"));
	}
}
